package com.e2edour.runtime.properties

import java.io.{File, FileInputStream}
import java.util.{Properties, ResourceBundle}

import org.slf4j.LoggerFactory

/**
  * <p>
  *
  * @author King 
  * @since 2017/1/17
  */
object PropertiesConfig {

  private var DEFAULT_CONF_FILE = File.separator + "wls" + File.separator + "envconfig" + File.separator + "env.properties"

  private val DEFAULT_CONF_FILE_LOCAL = "env.properties"

  private val logger = LoggerFactory.getLogger(PropertiesConfig.getClass)

  def loadFile: Properties = {
    logger.info("<<<=================开始加载配置项=================>>>")
    val properties = new Properties
    properties.putAll(loadWarFile)
    if (properties.containsKey("app.name")) {
      val appName = properties.getProperty("app.name")
      DEFAULT_CONF_FILE = File.separator + "wls" + File.separator + "envconfig" + File.separator + appName + File.separator + "env.properties"
    }
    properties.putAll(loadOutFile(DEFAULT_CONF_FILE))
    val it = properties.keySet.iterator
    while (it.hasNext) {
      val key = it.next
      val keyStr = key.toString
      val value = properties.getProperty(keyStr)
      if ((null != keyStr) && (!keyStr.isEmpty)) AppContextConfig.put(keyStr, value)
    }
    import scala.collection.JavaConversions._
    for (me <- AppContextConfig.getConfigMap.entrySet) {
      logger.info(me.getKey + "=" + me.getValue)
    }
    logger.info("<<<=================配置项加载完毕=================>>>")
    properties
  }

  private def loadWarFile = {
    val properties = new Properties
    val input = Thread.currentThread.getContextClassLoader.getResourceAsStream(DEFAULT_CONF_FILE_LOCAL)
    if (input == null) {
      val res = ResourceBundle.getBundle("env")
      val keys = res.keySet
      import scala.collection.JavaConversions._
      for (key <- keys) {
        properties.put(key, res.getString(key))
      }
    }
    else properties.load(input)
    input.close
    properties
  }

  private def loadOutFile(filePath: String) = {
    val properties = new Properties
    try {
      val input = new FileInputStream(filePath)
      properties.load(input)
      input.close();
      properties
    } catch {
      case e: Exception =>
        e.printStackTrace
        properties
    }
  }
}
